﻿using System.Data;
using System.Linq;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Travasto.Model;

namespace Travasto.Web.Areas.Admin.Commands
{
    public class UpdateTourCommand
    {
        public TravastoDbContext DbContext { get; set; }
        public Tour Tour { get; set; }

        public UpdateTourCommand(Tour tour, TravastoDbContext context)
        {
            this.Tour = tour;
            this.DbContext = context;
        }

        public void Execute()
        {
            // Save tags
            this.Tour.Tags = (new AddTagsCommand(this.Tour.Tags, DbContext)).Execute();

            // Update tours
            var originalTour = DbContext.Tours.Single(t => t.TourId == Tour.TourId);
            if (originalTour != null)
            {
                // Update Tour
                DbContext.Entry(originalTour).CurrentValues.SetValues(Tour);

                // Update Tags
                if (originalTour.Tags != null) 
                    originalTour.Tags.Clear();
                
                originalTour.Tags = Tour.Tags;

                // Update Packages
                if (originalTour.Packages != null) 
                    originalTour.Packages.Clear();
                
                originalTour.Packages = Tour.Packages;
                
                // Save to database
                DbContext.SaveChanges();
            }

        }
    }
}